'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async login() {
    const { ctx, app, service, config } = this;
    const bodyRule = {
      mobile: { type: 'mobile' },
      password: { type: 'string' },
    };
    ctx.validate(bodyRule); // 校验参数
    const jwtConfig = config.jwt;
    const { helper } = ctx;
    const body = ctx.request.body;
    body.password = helper.encryptPwd(body.password);

    const result = await service.user.login(body);
    if (!result) return ctx.failure('账号或密码错误');
    result._doc.token = app.jwt.sign(result._doc, jwtConfig.secret, { expiresIn: '1d' }); // 生成token,有效期1天
    ctx.success('登录成功', result);
  }

  async save() {
    const { ctx, service } = this;
    const { helper } = ctx;
    const body = ctx.request.body;
    if (!body._id) {
      const saveRule = {
        name: { type: 'string' },
        mobile: { type: 'string' },
        password: { type: 'string' },
      };
      // 校验参数
      ctx.validate(saveRule);
    }
    // 调用 Service 进行业务处理
    if (body.password) {
      body.password = helper.encryptPwd(body.password);
    }
    const result = await service.user.save(body);
    // 设置响应内容和响应状态码
    ctx.success('注册成功', result);
  }

  async find() {
    const { ctx, service } = this;
    const body = ctx.request.body;
    const page = body.page || 1;
    const limit = body.limit || 10;
    const result = await service.user.find(body, page, limit);
    this.ctx.success('成功', result, result.length);
  }

  async userInfo() {
    const { ctx, service } = this;
    const { user } = ctx.state;
    try {
      const userInfo = await service.user.find({ _id: user._id });
      let roleIds = []; // 角色ids
      userInfo.forEach(item => {
        roleIds.push(item.roleIdList.join(',')); // 合并角色id
      });
      roleIds = Array.from(new Set(roleIds)); // 数组去重
      const ruleList = await service.role.findById(roleIds);
      let permissionIdLists = [];
      ruleList.forEach(item => {
        permissionIdLists.push(item.permissionIdList.join(','));
      });
      permissionIdLists = Array.from(new Set(permissionIdLists)); // 数组去重
      permissionIdLists = permissionIdLists.join(',')
        .split(','); // 数组转字符串后再转成数组
      user.ruleList = await service.permission.findById(permissionIdLists); // 菜单数据
      this.ctx.success('成功', user);
    } catch (error) {
      return ctx.failure(error.message);
    }
  }

  async logout() {
    const { ctx } = this;
    ctx.success('退出成功');
  }

}

module.exports = UserController;
